import 'dart:io';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:file_saver/file_saver.dart';
import 'package:filelinker/file_model.dart';
import 'package:filelinker/mdsn.dart';
import 'package:filelinker/netsev.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';

class RecivePage extends StatefulWidget {
  const RecivePage({super.key});

  @override
  State<RecivePage> createState() => _RecivePageState();
}

class _RecivePageState extends State<RecivePage> {
  @override
  void dispose() {
    NetService.shared.recvFiles.clear();
    super.dispose();
  }

  @override
  void initState() {
    NetService.shared.onGetFileNames = _onGetFileNames;
    NetService.shared.onRecvFile = () {
      if (mounted) setState(() {});
    };
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bool isDesktop = MDNS.shared.isDesktop;
    TextStyle? ts = isDesktop ? Theme.of(context).textTheme.titleSmall : null;
    return Scaffold(
      appBar: AppBar(
        leading: isDesktop ? const CloseButton() : null,
        title: Text("文件接收", style: ts),
        actions: [
          if (MDNS.shared.isDesktop || Platform.isAndroid) ...[
            TextButton(
              onPressed: _didTapOpenFolder,
              child: const Text(
                "打开文件夹",
              ),
            ),
          ],
        ],
      ),
      body: _wMainView(),
    );
  }

  Widget _wMainView() {
    if (Platform.isAndroid || MDNS.shared.isDesktop) {
      return Column(
        children: [
          Container(
            height: 40,
            color: Theme.of(context).primaryColor.withAlpha((0.25 * 255).round()),
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              children: [
                Text(
                  "保存路径: ",
                  style: Theme.of(context).textTheme.titleSmall?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
                const Gap(5),
                Expanded(
                  child: AutoSizeText(
                    NetService.shared.downloadFolder,
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                    ),
                    maxLines: 1,
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: _wBodyView(),
          ),
        ],
      );
    } else {
      return _wBodyView();
    }
  }

  Widget _wBodyView() {
    final List<RecvFile> files = NetService.shared.recvFiles;
    return ListView.separated(
      itemBuilder: (_, idx) {
        final file = files[idx];
        return ListTile(
          leading: Icon(
            isImage(file.name) ? Icons.image : Icons.description,
          ),
          title: Text(
            file.name,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
          trailing: _wStatusView(file),
        );
      },
      itemCount: files.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          color: Theme.of(context).primaryColor.withAlpha((0.25 * 255).round()),
          height: 0.25,
        );
      },
    );
  }

  Widget _wStatusView(RecvFile file) {
    final colorScheme = Theme.of(context).colorScheme;
    return !file.isRecvied
        ? SizedBox.fromSize(
            size: const Size(20, 20),
            child: CircularProgressIndicator(
              backgroundColor: colorScheme.primary.withAlpha((0.25 * 255).round()),
              value: file.progress,
            ),
          )
        : Icon(
            Icons.done,
            color: Theme.of(context).primaryColor,
          );
  }

  void _onGetFileNames() {
    setState(() {});
  }

  void _didTapOpenFolder() {
    final folder = NetService.shared.downloadFolder;
    debugPrint(folder);
    if (Platform.isWindows) {
      Process.run('explorer', [folder], workingDirectory: folder);
    } else if (Platform.isMacOS) {
      Process.run("open", [folder]);
    } else if (Platform.isAndroid) {
      FileSaver.instance.openFolder(folder);
    }
  }
}
